#include <QDateTime>
#include "common.h"
#include "mainwidget.h"
#include "ui_mainwidget.h"

extern volatile bool isSaveVideo;
extern volatile bool isSavePic;

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
{
    ui->setupUi(this);

#if defined(Q_OS_UNIX)
    this->setWindowState(Qt::WindowFullScreen);
#endif

    m_viewFinder = new QCameraViewfinder(this);
    m_viewFinder->setWindowFlag(Qt::FramelessWindowHint);
    m_viewFinder->setFixedSize(1280, 720);

    vd = new VideoDevice(m_viewFinder);

    videoThread = new VideoRecordThread(vd);
    pictureThread = new PictureRecordThread(vd);

    if (!videoThread->isRunning())
        videoThread->start();
    if (!pictureThread->isRunning())
        pictureThread->start();
}

MainWidget::~MainWidget()
{
    videoThread->stop();
    if (videoThread->isFinished())
        delete videoThread;
    pictureThread->stop();
    if (pictureThread->isFinished())
        delete pictureThread;

    delete vd;
    vd = nullptr;
    delete m_viewFinder;
    delete ui;
}

void MainWidget::on_pictureBtn_clicked()
{
    isSavePic = true;
    usleep(5*1000);
}

void MainWidget::on_videoBtn_clicked()
{
    if (isSaveVideo == false)
    {
        qDebug()<<"video start";
        QDateTime saveTime =  QDateTime::currentDateTime();

        QString str = "/usr/app/zhangya/"+saveTime.toString("yyyyMMdd_hhmmss")+".mp4";
        VideoEncode::open(str, VIDEO_WIDTH, VIDEO_HEIGHT, VIDEO_FPS);
        isSaveVideo = true;
    }else{
        isSaveVideo = false;
        qDebug()<<"video stop";
        VideoEncode::close();
    }
}
